package me.zhengjie.modules.pay.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.exception.BizException;
import me.zhengjie.modules.pay.domain.req.BuyProductReq;
import me.zhengjie.modules.pay.domain.req.OpenVipReq;
import me.zhengjie.modules.biz.domain.resp.WxPayResp;
import me.zhengjie.modules.pay.domain.req.RefundReq;
import me.zhengjie.modules.pay.domain.req.WxPayReq;
import me.zhengjie.modules.pay.service.WxPayService;
import org.apache.ibatis.annotations.Param;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@Api(tags = "支付模块：微信支付")
@RequestMapping("/api/wx")
@Slf4j
public class WxPayController {

    private final WxPayService wxPayService;

    @PostMapping("/pay")
    @Log("微信支付(开通VIP)")
    @ApiOperation("开通vip")
    public ResponseEntity<WxPayResp> openVip(@RequestBody OpenVipReq openVipReq) throws Exception {
        log.info("/api/wx/pay 请求参数：{}",openVipReq);
        return new ResponseEntity<>(wxPayService.openVip(openVipReq), HttpStatus.OK);
    }

    @GetMapping("/buy/{orderSn}")
    @Log("购买商品")
    @ApiOperation("购买商品")
    public ResponseEntity<WxPayResp> buy(@PathVariable String orderSn) throws Exception {
        log.info("/api/wx/buy/{}",orderSn);
        return new ResponseEntity<>(wxPayService.buy(orderSn), HttpStatus.OK);
    }

    @PostMapping("/queryOrder")
    @Log("查询订单")
    @ApiOperation("查询订单")
    public ResponseEntity<Object> queryOrderById(@RequestBody WxPayReq wxPayReq) throws Exception {
        log.info("/api/wx/queryOrder 查询订单：{}",wxPayReq);
        wxPayService.queryOrder(wxPayReq);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/closeOrder")
    @Log("取消订单")
    @ApiOperation("取消订单")
    public ResponseEntity<Object> closeOrder(@RequestBody WxPayReq wxPayReq) throws BizException {
        log.info("/api/wx/closeOrder 取消订单：{}",wxPayReq);
        return new ResponseEntity<>(wxPayService.closeOrder(wxPayReq),HttpStatus.OK);
    }

    @AnonymousAccess
    @PostMapping("/wxPayNotify")
    @Log("微信支付回调")
    @ApiOperation("微信支付回调")
    public void wxPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 从请求中读取微信支付通知内容
        ServletInputStream inputStream = request.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        inputStream.close();
        String notifyXml = sb.toString();

        // 处理微信支付通知
        wxPayService.wxPayNotify(notifyXml);

        // 返回成功响应
        response.setContentType("text/xml");
        PrintWriter writer = response.getWriter();
        writer.write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
        writer.flush();
        writer.close();
    }

    @PostMapping("/refund")
    @Log("申请退款")
    @ApiOperation("申请退款")
    public ResponseEntity<Object> refund(@RequestBody RefundReq req) throws BizException {
        log.info("/api/wx/refund 申请退款：{}",req);
        wxPayService.refundOrder(req);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @AnonymousAccess
    @PostMapping("/refundNotify")
    @Log("微信退款回调")
    @ApiOperation("微信退款回调")
    public Object refundNotify(HttpServletRequest request) throws Exception {
        // 从请求中读取微信支付通知内容
        ServletInputStream inputStream = request.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        inputStream.close();
        String notifyXml = sb.toString();
        // 处理微信支付通知
        wxPayService.refundNotify(notifyXml);
        Map<String, Object> parm = new HashMap<>();
        // 先默认为成功
        parm.put("code", "SUCCESS");
        parm.put("message", "成功");
        return parm;
    }

}
